import React, { useCallback, useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import {
  Image,
  KeyboardAvoidingView,
  Modal,
  ModalProps,
  Platform,
  Pressable,
  StyleSheet,
  Text,
  Touchable,
  TouchableOpacityProps,
  TouchableWithoutFeedback,
  View,
} from "react-native";
import { Input } from "../Form/Input/Input";
import { Label } from "../Form/Input/styles";
import { Header } from "../Header";

import { Button } from "../Button/Button";
import * as S from "./styles";
import /*RFValue*/ "react-native-responsive-fontsize";
import { ImageMap } from "../../constants/categories";
import { times } from "../../constants/times";
import moment from "moment";
import { showToast } from "../../utils/toast";
import { useTasks } from "../../hooks/useTasks";
import { useCategory } from "../../hooks/useCategory";
import EventContent from "./event";
import Toast from "react-native-toast-notifications";
import { toastConfig } from "../../utils/config";
import { countDecimalPlaces } from "../../utils/utils";
import { TouchableOpacity } from "react-native-gesture-handler";

interface FormData {
  event: string;
  mood: number;
  time: string;
  remark: string;
}

interface TaskModalProps extends ModalProps {
  title: string;
  visable: boolean;
  toggleModal?: () => void;
  onCancel?: () => void;
}

interface ButtonProps extends TouchableOpacityProps {
  children: string;
  type?: string;
  active?: boolean;
}

const CategoryBtn = ({
  type,
  active = false,
  children,
  selectedMood = "",
  ...rest
}: ButtonProps) => {
  // const url = ImageMap.find((image) => {
  //   return image.name === type;
  // })?.url;
  return (
    <S.ButtonsContainer onPress={rest.onPress} activeOpacity={0.7} {...rest}>
      {type && active && (
        // <Image
        //   source={url}
        //   style={{
        //     width: 20,
        //     height: 20,
        //   }}
        // />
        <View
          style={[
            { width: 6, height: 6, borderRadius: 100, marginRight: 4 },
            {
              backgroundColor:
                selectedMood == 1
                  ? "rgba(255, 141, 26, 1)"
                  : selectedMood == 2
                  ? "rgba(67, 207, 124, 1)"
                  : selectedMood == 3
                  ? "rgba(142, 142, 147, 1)"
                  : "",
            },
          ]}
        ></View>
      )}
      <S.ButtonText
        style={[
          active && { fontWeight: "700" },
          {
            color: active
              ? selectedMood == 1
                ? "rgba(255, 141, 26, 1)"
                : selectedMood == 2
                ? "rgba(67, 207, 124, 1)"
                : selectedMood == 3
                ? "rgba(142, 142, 147, 1)"
                : "rgba(227, 73, 73, 1)"
              : "rgba(72, 72, 74, 1)",
          },
        ]}
      >
        {children}
      </S.ButtonText>
    </S.ButtonsContainer>
  );
};

function findNameById(categorys, id) {
  let name = "";
  categorys.forEach((cg1) => {
    if (cg1.id === id) {
      name = cg1.name + ">";
    } else if (cg1.children) {
      cg1.children.forEach((cg2) => {
        if (cg2.id === id) {
          name = cg1.name + ">" + cg2.name + ">";
        } else if (cg2.children) {
          cg2.children.forEach((cg3) => {
            if (cg3.id === id) {
              name = cg1.name + ">" + cg2.name + ">" + cg3.name;
            }
          });
        }
      });
    }
  });
  return name;
}

export function TaskModal({
  title,
  // selectedTaskId,
  onCancel,
  visible,
}: TaskModalProps) {
  const {
    loadTasks,
    createTask,
    updateTask,
    selectedTaskId,
    updateSelectedTaskId,
    activeDate,
    updateActiveDate,
    startDate,
    endDate,
  } = useTasks();
  const {
    selectedCategoryId,
    updateSelectedCategoryId,
    categorys,
    updateSelectedStatus,
  } = useCategory();
  const [selectedTime, setselectedTime] = useState(selectedTaskId?.time || "");
  const [selectedMood, setselectedMood] = useState(selectedTaskId?.mood || 0);
  const [remarks, setRemarks] = useState(selectedTaskId?.remark || "");

  const [eventVis, setEventVis] = useState(false);
  const [selectedEvent, setselectedEvent] = useState(null);
  const [initEvent, setInitEvent] = useState(null);
  const modalToastRef = React.useRef();

  function resetValues() {
    setselectedMood(0);
    setselectedTime("");
    setRemarks("");
    setValue("remark", "");
    setValue("time", "");
    setValue("mood", 0);
    categoryString = null;
    updateSelectedCategoryId(null);
    setselectedEvent(null);
    updateSelectedTaskId(null);
    updateSelectedStatus(false);
  }

  // 传入的事件
  let categoryString = "请选择分类";
  if (selectedCategoryId) {
    const { eventId, id } = selectedCategoryId;
    categoryString = findNameById(categorys, eventId || id);
  }

  //  编辑
  if (selectedTaskId) {
    const {
      fatherId,
      mood,
      time,
      remark,
      eventOneName,
      eventTwoName,
      eventThreeName,
    } = selectedTaskId;
    categoryString = findNameById(categorys, fatherId);
    categoryString = eventOneName + ">";
    if (eventTwoName) categoryString += eventTwoName + ">";
    if (eventThreeName) categoryString += eventThreeName;

    if (!selectedTime) {
      setselectedMood(mood);
      setselectedTime(time);
      setRemarks(remark);
    }
  }

  // 选择的事件
  if (selectedEvent && selectedEvent.id) {
    categoryString = findNameById(categorys, selectedEvent.id);
  }

  const {
    control,
    formState: { errors },
    getValues,
    setValue,
  } = useForm<FormData>({});

  let {
    id = undefined,
    eventId = undefined,
    name = undefined,
    eventName = undefined,
    eventType = undefined,
  } = selectedCategoryId || {};

  const selectOptions = useMemo(() => {
    return times.map((time) => ({
      value: time.key,
      label: time.label,
    }));
  }, []);

  const handleAddNewTask = useCallback(() => {
    if (!categoryString || categoryString === "请选择分类") {
      modalToastRef.current.show("请选择分类", {
        type: "normal",
        placement: "top",
        offset: 68,
      });

      return;
    }
    if (!selectedTime && !getValues("time")) {
      modalToastRef.current.show("请选择时长", {
        type: "normal",
        placement: "top",
        offset: 68,
      });
      return;
    }
    if (!selectedMood) {
      modalToastRef.current.show("请选择效率", {
        type: "normal",
        placement: "top",
        offset: 68,
      });
      return;
    }

    // 更新
    onCancel();
    if (selectedTaskId) {
      let { id, fatherId, event, eventType, dateStr } = selectedTaskId;
      if (selectedEvent) {
        fatherId = selectedEvent.id;
        eventType = selectedEvent.eventType;
        event = selectedEvent.name;
      }
      const updateParams = {
        id,
        fatherId,
        event,
        eventType,
        mood: selectedMood,
        time: getValues("time") || selectedTime,
        remark: getValues("remark") || remarks,
      };
      updateTask(updateParams)
        .then(function () {
          // handle success
          showToast("success", "提示", "更新记录成功");
          onCancel();
          loadTasks({
            startDate: moment(endDate).format("YYYY-MM-DD"),
            endDate: moment(startDate).format("YYYY-MM-DD"),
          });
        })
        .catch((data) => {
          showToast("error", "出错了", data.msg);
        });
    } else if (selectedCategoryId || selectedEvent) {
      if (selectedEvent) {
        id = selectedEvent.id;
        eventType = selectedEvent.eventType;
        name = selectedEvent.name;
      }
      const params = {
        fatherId: eventName ? eventId : id,
        eventType: eventType,
        dateStr: activeDate,
        addTimeStr: moment().format("HH:mm"),
        mood: selectedMood,
        time: getValues("time") || selectedTime,
        remark: getValues("remark"),
        event: eventName ? eventName : name,
      };
      createTask(params)
        .then(function () {
          // handle success
          onCancel();
          showToast("success", "提示", "创建记录成功");
          loadTasks({
            startDate: moment(endDate).format("YYYY-MM-DD"),
            endDate: moment(startDate).format("YYYY-MM-DD"),
          });
        })
        .catch((data) => {
          showToast("error", "出错了", data.msg);
        });
    }
    // 表单状态&传入值置空
    resetValues();
  }, [
    selectedCategoryId,
    // selectedTaskId,
    selectedEvent,
    selectedMood,
    selectedTime,
    remarks,
  ]);

  return (
    <View>
      <Modal
        animationType="slide"
        transparent={true}
        visible={visible}
        presentationStyle="overFullScreen"
      >
        <Toast
          ref={modalToastRef}
          renderType={{
            normal: toastConfig.modalInfo,
          }}
          offsetTop={68}
        />
        <TouchableWithoutFeedback
          onPress={(e) => {
            onCancel();
            resetValues();
          }}
        >
          <S.ModalOverlay>
            <KeyboardAvoidingView
              enabled={Platform.OS == "ios"}
              behavior={"padding"}
              style={styles.modalView}
            >
              {!eventVis ? (
                <TouchableWithoutFeedback onPress={(e) => e.stopPropagation()}>
                  <View>
                  <Header
                    icon={{
                      type: "close",
                      action: () => {
                        onCancel();
                        resetValues();
                      },
                    }}
                    title={title}
                    // style={{ height: /*RFValue*/ 72 }}
                  />
                  <S.ModalContentContainer>
                    <S.InputsWrapper
                      style={{
                        borderTopLeftRadius: /*RFValue*/ 16,
                        borderTopRightRadius: /*RFValue*/ 16,
                      }}
                    >
                      <Controller
                        control={control}
                        rules={{
                          required: false,
                        }}
                        render={({}) => (
                          <View
                            style={{
                              flexDirection: "row",
                              justifyContent: "space-between",
                              alignItems: "center",
                              flexWrap: "nowrap",
                            }}
                          >
                            <Label style={styles.lableStyle}>分类</Label>
                            <View
                              style={{
                                flexDirection: "row",
                                justifyContent: "flex-end",
                                flexWrap: "nowrap",
                              }}
                            >
                              {categoryString.split(">").map((cg, index) => {
                                return (
                                  cg !== "" && (
                                    <Pressable
                                      key={index}
                                      style={{
                                        flexDirection: "row",
                                        alignItems: "center",
                                      }}
                                      onPress={() => {
                                        // onCancel();
                                        setInitEvent({
                                          level: index + 1,
                                          name: categoryString.split(">")[
                                            index - 1
                                          ],
                                        });
                                        setEventVis(true);
                                      }}
                                    >
                                      <Text
                                        numberOfLines={1}
                                        ellipsizeMode="tail"
                                        style={{
                                          justifyContent: "flex-end",
                                          maxWidth: /*RFValue*/ 60,
                                          color: "rgba(65, 79, 102, 1)",
                                          fontSize: /*RFValue*/ 14,
                                          // marginLeft: /*RFValue*/ 12,
                                          fontWeight: "500",
                                          fontFamily:
                                            "HarmonyOS_Sans_SC_Regular",
                                        }}
                                      >
                                        {cg}
                                      </Text>
                                      <S.Icon
                                        name="chevron-right"
                                        size={14}
                                        color="rgba(65, 79, 102, 1)"
                                      />
                                    </Pressable>
                                  )
                                );
                              })}
                            </View>
                          </View>
                        )}
                        name="event"
                      />
                    </S.InputsWrapper>
                    <S.InputsWrapper
                      style={{
                        height: "auto",
                        paddingVertical: /*RFValue*/ 16,
                        alignItems: "center",
                        alignContent: "center",
                        paddingTop: 14,
                        paddingBottom: 14,
                      }}
                    >
                      <Controller
                        control={control}
                        rules={{
                          required: true,
                          maxLength: 200,
                        }}
                        defaultValue={remarks}
                        render={({ field: { onChange, onBlur, value } }) => (
                          <Input
                            label="备注"
                            maxLength={200}
                            onBlur={onBlur}
                            onChangeText={onChange}
                            value={value}
                            placeholderTextColor="rgba(174, 174, 178, 1)"
                            placeholder="点击输入"
                            error={errors.title?.message}
                          />
                        )}
                        name="remark"
                      />
                    </S.InputsWrapper>
                    <S.InputsWrapper>
                      <Controller
                        control={control}
                        rules={{
                          required: true,
                        }}
                        defaultValue={selectedTime}
                        render={({ field: { onChange, onBlur, value } }) => (
                          <View>
                            <Input
                              label="时长/h"
                              onBlur={onBlur}
                              onChangeText={(v) => {
                                const num = Number(v);
                                if (isNaN(num)) {
                                  modalToastRef.current.show("请输入0-24数字", {
                                    type: "normal",
                                    placement: "top",
                                    offset: 68,
                                  });
                                  return;
                                }
                                if (num < 0) {
                                  modalToastRef.current.show("请输入0-24数字", {
                                    type: "normal",
                                    placement: "top",
                                    offset: 68,
                                  });
                                  setValue("time", "");
                                  setselectedTime("");
                                  return;
                                } else if (num > 24) {
                                  modalToastRef.current.show("请输入0-24数字", {
                                    type: "normal",
                                    placement: "top",
                                    offset: 68,
                                  });
                                  setValue("time", "");
                                  setselectedTime("");
                                  return;
                                } else {
                                  countDecimalPlaces(v) > 1
                                    ? setselectedTime(num.toFixed(1))
                                    : setselectedTime(v);
                                  countDecimalPlaces(v) > 1
                                    ? onChange(num.toFixed(1))
                                    : onChange(v);
                                }
                              }}
                              value={value}
                              keyboardType="numeric"
                              placeholder="点击输入时长"
                              placeholderTextColor="rgba(174, 174, 178, 1)"
                              error={errors.title?.message}
                            />
                            <View
                              style={{
                                flexDirection: "row",
                                justifyContent: "space-between",
                                alignItems: "center",
                                marginTop: 12,
                              }}
                            >
                              {selectOptions.map((option) => {
                                return (
                                  <CategoryBtn
                                    style={
                                      selectedTime === option.value
                                        ? styles.selected
                                        : styles.notSelected
                                    }
                                    active={selectedTime === option.value}
                                    key={option.value}
                                    onPress={() => {
                                      setValue("time", option.value);
                                      setselectedTime(option.value);
                                    }}
                                  >
                                    {option.label}
                                  </CategoryBtn>
                                );
                              })}
                            </View>
                          </View>
                        )}
                        name="time"
                      />
                    </S.InputsWrapper>
                    <S.InputsWrapper
                      style={{
                        borderBottomLeftRadius: /*RFValue*/ 16,
                        borderBottomRightRadius: /*RFValue*/ 16,
                      }}
                    >
                      <Controller
                        control={control}
                        rules={{
                          required: true,
                        }}
                        render={({}) => (
                          <View
                            style={{
                              flexDirection: "row",
                              justifyContent: "space-between",
                              alignItems: "center",
                            }}
                          >
                            <Label style={styles.lableStyle}>时间效率</Label>
                            <CategoryBtn
                              key={1}
                              onPress={() => {
                                setselectedMood(1);
                                setValue("mood", 1);
                              }}
                              style={[
                                selectedMood === 1
                                  ? styles.selected
                                  : styles.notSelected,
                                // { height: /*RFValue*/ 36 },
                                {
                                  backgroundColor:
                                    selectedMood === 1
                                      ? "rgba(255, 141, 26, 0.16)"
                                      : "rgba(236, 236, 236, 1)",
                                },
                              ]}
                              active={selectedMood === 1}
                              type="smail"
                              selectedMood={selectedMood}
                            >
                              高
                            </CategoryBtn>
                            <CategoryBtn
                              key={2}
                              onPress={() => {
                                setselectedMood(2);
                                setValue("mood", 2);
                              }}
                              style={[
                                selectedMood === 2
                                  ? styles.selected
                                  : styles.notSelected,
                                  {
                                    backgroundColor :selectedMood === 2 ? 'rgba(67, 207, 124, 0.16)' : 'rgba(236, 236, 236, 1)'
                                  },
                                // { height: /*RFValue*/ 36 },
                              ]}
                              active={selectedMood === 2}
                              type="cry"
                              selectedMood={selectedMood}
                            >
                              中
                            </CategoryBtn>
                            <CategoryBtn
                              key={3}
                              onPress={() => {
                                setselectedMood(3);
                                setValue("mood", 3);
                              }}
                              style={[
                                selectedMood === 3
                                  ? styles.selected
                                  : styles.notSelected,
                                  {
                                    backgroundColor :selectedMood === 3 ? 'rgba(142, 142, 147, 0.16)' : 'rgba(236, 236, 236, 1)'
                                  },
                                // { height: /*RFValue*/ 36 },
                              ]}
                              active={selectedMood === 3}
                              type="normal"
                              selectedMood={selectedMood}
                            >
                              低
                            </CategoryBtn>
                          </View>
                        )}
                        name="mood"
                      />
                    </S.InputsWrapper>

                    <S.ButtonsWrapper>
                      <S.ButtonContainer>
                        <Button
                          activeOpacity={0.7}
                          // disabled={true}
                          // onPress={handleSubmit(handleAddNewTask)}
                          onPress={handleAddNewTask}
                        >
                          {selectedTaskId ? "更新记录" : "新增记录"}
                        </Button>
                      </S.ButtonContainer>
                    </S.ButtonsWrapper>
                  </S.ModalContentContainer>
                </View>
                </TouchableWithoutFeedback>
              ) : (
                <TouchableWithoutFeedback onPress={(e) => e.stopPropagation()}>
                <EventContent
                  initEvent={initEvent}
                  selectedEvent={(e: React.SetStateAction<null>) =>
                    setselectedEvent(e)
                  }
                  closeFun={() => setEventVis(false)}
                />
                </TouchableWithoutFeedback>
              )}
            </KeyboardAvoidingView>
          </S.ModalOverlay>
        </TouchableWithoutFeedback>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  modalView: {
    flex: 1,
    backgroundColor: "white",
    borderTopLeftRadius: /*RFValue*/ 24,
    borderTopRightRadius: /*RFValue*/ 24,
    // height: "68%",
    width: "100%",
    position: "absolute",
    bottom: 0,
    // alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  button: {
    borderRadius: 20,
    padding: 10,
    elevation: 2,
  },
  buttonOpen: {
    backgroundColor: "#F194FF",
  },
  buttonClose: {
    backgroundColor: "#2196F3",
  },
  lableStyle: {
    width: /*RFValue*/ 72,
    fontFamily: "HarmonyOS_Sans_SC_Regular",
    fontWeight: "700",
    color: "rgba(28, 28, 30, 1)",
  },
  textStyle: {
    color: "white",
    fontWeight: "bold",
    textAlign: "center",
  },
  modalText: {
    marginBottom: 15,
    textAlign: "center",
  },
  selected: {
    backgroundColor: "rgba(227, 73, 73, 0.16)",
    borderRadius: /*RFValue*/ 12,
    width: "22%",
    height: /*RFValue*/ 32,
  },
  notSelected: {
    backgroundColor: "rgba(236, 236, 236, 1)",
    borderRadius: /*RFValue*/ 12,
    width: "22%",
    height: /*RFValue*/ 32,
  },
});
